package org.wlgzs.office_exam_student.service.office;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.mchange.v2.sql.filter.SynchronizedFilterDataSource;
import org.wlgzs.office_exam_student.entity.OperateQuestion;
import org.wlgzs.office_exam_student.service.OperateQuestionService;

import com.songminju.jdagger.JDCheck;

/**
*@author song(mejeesong@qq.com)
*2018年1月30日
*
*/
public class OfficeConfig {
	
	public enum FileType{
		DOCX,XLSX,PPTX;
	}
	public enum PaperType{
		MOCK,TEST;
	}

	public static String CHOICE_IMG_PATH = "";
	public static String TEMP_DIR = "/opt/temp/";
	public static String DIST_DIR = "/opt/temp/dist/";
	
	public static final String FILETYPE_DOCX = "docx";
	public static final String FILETYPE_XLSX = "xlsx";
	public static final String FILETYPE_PPTX = "pptx";
	public static final long CLEAN_DUR = 3600 * 1000 *24 * 10;
	public static final Map<Integer,String> keys = new HashMap<>();
	public static final OperateQuestionService oqs = new OperateQuestionService();
	static {
        Properties pro = new Properties();
        try {
            pro.load(OfficeConfig.class.getClassLoader().getResourceAsStream("office.properties"));
            TEMP_DIR = String.valueOf(pro.get("TEMP_DIR"));
            DIST_DIR = String.valueOf(pro.get("DIST_DIR"));
            CHOICE_IMG_PATH = String.valueOf(pro.get("CHOICE_IMG_PATH"));
            if(!TEMP_DIR.endsWith(File.separator)){
                TEMP_DIR += File.separator;
            }
            if(!DIST_DIR.endsWith(File.separator)){
                DIST_DIR += File.separator;
            }
            if(!CHOICE_IMG_PATH.endsWith(File.separator)){
                CHOICE_IMG_PATH += File.separator;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        List<OperateQuestion> qs = oqs.queryAll();
		for(OperateQuestion q:qs) {
			keys.put(q.getId(),q.getSourceUrl());
		}

	}
	
	public static final void clean() {
		clean_each(new File(DIST_DIR));
	}
	
	private static final void clean_each(File file) {
		if(file == null)
			return;
		if(file.isFile()) {
			long now = System.currentTimeMillis();
			long x = file.lastModified();
			
			if(now - x > CLEAN_DUR) {
				file.delete();
			}
		}else if(file.isDirectory()) {
			long now = System.currentTimeMillis();
			long x = file.lastModified();
			if((!file.getAbsolutePath().equals(DIST_DIR)) && now-x>CLEAN_DUR) {
				file.delete();
			}else {
				for(File f:file.listFiles()) {
					clean_each(f);
				}
			}
		}
	}

	public static String generateKey(int id){
		String key =  keys.get(id);
		if(JDCheck.hasNsNull(key)) {
			OperateQuestion q = oqs.operateQuestion(id);
			key = (q==null?null:q.getSourceUrl());
		}
		return key;
	}

	public static String resolveFileDir(ResolveTask task) {
		if(task == null) {
			return null;
		}
		return resolveFileDir(task.getUserId(),task.getExamId(),task.getIndex(),task.getFileType());
	}
	public static String resolveFileDir(int userId,int examId,int index,FileType fileType) {
		
		switch (fileType) {
		case DOCX:
			return resolveFileDir(userId, examId, index, FILETYPE_DOCX);
		case XLSX:
			return resolveFileDir(userId, examId, index, FILETYPE_XLSX);
		case PPTX:
			return resolveFileDir(userId, examId, index, FILETYPE_PPTX);
		}
		return null;
	}
	
	public static String resolveFileDir(int userId,int examId,int index,String fileType) {
		if(fileType == null) {
			return null;
		}
		StringBuilder dir = new StringBuilder(DIST_DIR);
		dir.append(userId).append(File.separator).append(examId).append(File.separator);
		dir.append(fileType).append("-").append(index);
		return dir.toString();
	}
	
	private static String[] getFiles(String sourceUrl) {
		URL url = OfficeConfig.class.getClassLoader().getResource("questions/"+sourceUrl);
		if(url == null || url.getFile() == null) {
			return null;
		}
		File file = new File(url.getFile());
		if(file.exists() && file.isDirectory()) {
			return file.list();
		}
		return null;
	}
	public static String renderFiles(String sourceUrl) {
		String[] files = getFiles(sourceUrl);
		if(files == null) {
			return "未找到此题试卷,请练习管理员+"+sourceUrl;
		}
		StringBuilder sb = new StringBuilder();
		for(String s:files) {
			sb.append(String.format("<a  class=\"layui-btn layui-btn-sm layui-btn-primary\" href=\"static/questions/%s/%s\">%s</a>", sourceUrl,s,s));
		}
		return sb.toString();
	}
	
}
